<?php
/**
* Загрузчик приложения. Реализован как singleton.
*/

class Engine_Bootstrap {
	protected static $__instance = null;
	protected static $__config = null;
	protected static $__dbAdapter = null;
	protected static $__request = null;
    protected static $__activeUser = null;

	protected function __construct() {}
	protected function __clone() {}
	protected function __wakeup() {}

	public function getInstance() {
		if (self::$__instance === null) {
			self::$__instance = new self();
		}
		return self::$__instance;
	}

	//Инициализация конфига
	protected static function initConfig($configPath = null) {
		if ($configPath === null) {
			throw new Exception("Configuration unknown", 404);
		}		
		self::$__config = parse_ini_file($_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'application' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . $configPath, true);
	}

	// Инициализация адаптера базы данных
	protected static function initDbAdapter($adapter) {
		$config = self::$__config;
		if (array_key_exists($adapter, $config)) {
			$dsn = $config[$adapter]['type'] . '://' 
					. $config[$adapter]['user'] . ':' 
					. $config[$adapter]['password'] . '@' 
					. $config[$adapter]['host'] . '/' 
					. $config[$adapter]['db'];
			$dbAdapter = DbSimple_Generic::connect($dsn);
			$dbAdapter->setErrorHandler('databaseErrorHandler');
            $dbAdapter->query('SET NAMES UTF8');
			if (!empty($dbAdapter->error)) {
				throw new Exception('Database adapter create error.', 404);
			} else {
				self::$__dbAdapter[$adapter] = $dbAdapter;
			}
		}
		
	}

	protected static function initActiveUser() {
        if (self::$__activeUser === null) {
            self::$__activeUser = new Engine_User_Active();
        }
	}

    protected  static function initHttpRequest() {
        if (self::$__request === null) {
            self::$__request = new Engine_Http_Request();
        }
    }


}